#include "SList.h"

SLTnode* Buynode(SLTDataType x)
{
	SLTnode* newnode = (SLTnode*)malloc(sizeof(SLTnode));

	if (newnode == NULL)
	{
		perror("buynode fail");
		return NULL;
	}
	newnode->data = x;
	newnode ->next= NULL;
	return newnode;
}
void SLTPrint(SLTnode* phead)
{
	SLTnode* tail = phead;
	while (tail)
	{
		printf("%d->", tail->data);
		tail = tail->next;
	}
	printf("NULL\n");
}

void SLPushFront(SLTnode** pphead, SLTDataType x)
{
	//assert(*pphead);
	assert(pphead);
	SLTnode* newnode = Buynode(x);

	newnode->next = *pphead;
	*pphead = newnode;

}

void SLPushBack(SLTnode** pphead, SLTDataType x)
{
	assert(pphead);

	SLTnode* newnode = Buynode(x);
	SLTnode* tail = *pphead;

	if (tail == NULL)
	{
		tail = newnode;
	}
	while (tail->next != NULL)
	{
		tail = tail->next;
	}
	tail->next = newnode;

}
void SLPopFront(SLTnode** pphead)
{
	SLTnode* newnode = *pphead;
	*pphead = (*pphead)->next;
	free(newnode);

}

void SLPopBack(SLTnode** pphead)
{
	assert(pphead);
	assert(*pphead);
	SLTnode* tail = *pphead;
	if ((*pphead)->next == NULL)
	{
		free(*pphead);
		*pphead = NULL;
	}

	while (tail->next->next)
	{
		tail = tail->next;
	}
	free(tail->next);
	tail->next = NULL;

}
SLTnode* SLFind(SLTnode* phead, SLTDataType x)
{
	SLTnode* cur = phead;
	while (cur)
	{
		if (cur->data == x)
		{
			return cur;
		}
		cur = cur->next;
	}
	return NULL;
}

void SLInsert(SLTnode** pphead, SLTnode* pos, SLTDataType x)
{
	SLTnode* prev = *pphead;
	SLTnode* newnode = Buynode(x);
	while (prev->next != pos)
	{
		prev = prev->next;
	}
	newnode->next = pos;
	prev->next = newnode;
}
void SLInsertAfter(SLTnode* pos, SLTDataType x)
{
	assert(pos);
	SLTnode* newnode = Buynode(x);

	newnode->next = pos->next;
	pos->next = newnode;

}
void SLErase(SLTnode** pphead, SLTnode* pos)
{
	SLTnode* del = *pphead;
	while (del->next != pos)
	{
		del = del->next;
	}
	del->next = pos->next;
	free(pos);
	pos = NULL;
}
void SLEraseAfter(SLTnode* pos)
{
	assert(pos);
	assert(pos->next);
	SLTnode* cur = pos->next;
	pos->next = cur->next;
	free(cur);
	
	
}